package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.business.BusinessDO;
import com.qk.dto.business.BusinessAddDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.dto.business.BusinessPoolListDTO;
import com.qk.dto.business.UpdateBusinessInfoDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 商机Service层实现类
 * @Author:Mr.m
 * @Date: 2025-10-15 11:03
 * @Description:
 */
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;

    /**
     * 商机公海列表
     *
     * @param dto 商机信息
     * @return 商机列表
     */
    @Override
    public PageResult<Business> businessPool(BusinessPoolListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<Business> list = this.baseMapper.selectPoolByPage(dto);
        Page<Business> page = (Page<Business>) list;
        PageResult<Business> result = PageResult.<Business>builder()
                .total(page.getTotal())
                .rows(list)
                .build();
        return result;
    }

    /**
     * 跟进商机信息
     *
     * @param dto 商机信息
     */
    @Override
    public void updateBusinessInfoById(UpdateBusinessInfoDTO dto) {
        //1.获取商机信息  更新商机信息 business表
        //1.1 将dto中属于business表信息拷贝过来
        Business business = BeanUtil.copyProperties(dto, Business.class);
        //1.2 补全更新时间
        business.setUpdateTime(LocalDateTime.now());
        //1.3 处理状态 待分配转变为跟进中
        if (business.getStatus() == (BusinessStatusConstants.WAIT_FOLLOW_UP)) {
            business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        }
        //1.4 更新business表信息
        this.baseMapper.updateById(business);
        //2. 添加商机记录  business_track_record表business_track_record
        BusinessTrackRecord record = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        //2.1 补全创建时间
        record.setCreateTime(LocalDateTime.now());
        //2.2 将id置为null
        record.setId(null);
        //2.3 设置当前商机跟进记录
        record.setBusinessId(business.getId());
//        //2.4 设置商机跟进记录状态  默认
//        record.setTrackStatus(BusinessStatusConstants.FOLLOW_UP);
        record.setUserId(CurrentUserContextHolders.get());
        //2.5 添加商机记录
        this.businessTrackRecordMapper.insert(record);
    }

    /**
     * 获取商机信息
     *
     * @param id 商机id
     * @return 商机信息
     */
    @Override
    public BusinessVO getBusinessInfoById(Integer id) {
        //1. 根据id查询线索表获取基础线索信息
        Business business = this.baseMapper.selectById(id);
        //2.根据用户id获取用户名
        Integer userId = business.getUserId();
        User user = userMapper.selectById(userId);
        //3.根据线索id查询线索记录表获取当前线索跟进记录
        List<BusinessTrackRecord> businessTrackRecords = businessTrackRecordMapper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                .in(BusinessTrackRecord::getBusinessId, id)
        );
        //4.组装数据
        BusinessVO businessVO = BeanUtil.copyProperties(business, BusinessVO.class);
        List<BusinessVO.BusinessTrackRecordVO> list = businessTrackRecords.stream().map(item -> {
            BusinessVO.BusinessTrackRecordVO vo = BeanUtil.copyProperties(item, BusinessVO.BusinessTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        //5. 设置跟进记录
        businessVO.setTrackRecords(list);
        return businessVO;
    }

    /**
     * 转用户
     *
     * @param id 商机id
     * @return 修改结果
     */
    @Transactional
    @Override
    public void toCustomer(Integer id) {
        //1.获取商机信息
        Business business = this.baseMapper.selectById(id);
        //2.修改商机状态为转成客户
        //2.1更新状态
        business.setStatus(BusinessStatusConstants.TO_CUSTOMER);
        //2.2更新时间
        business.setUpdateTime(LocalDateTime.now());
        //2.3更新business表数据
        this.baseMapper.updateById(business);

        //3.将线索信息组装成客户信息  添加到客户表
        //3.1 拷贝同名属性到客户
        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        //3.2处理拷贝后的数据
        //3.2.1 客户id置为null
        customer.setId(null);
        //3.2.2 设置客户创建时间和修改时间
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        //3.2.3 设置商机id
        customer.setBusinessId(id);
        //3.3 添加到客户表
        this.customerMapper.insert( customer);

    }

    /**
     * 商机列表
     *
     * @param dto 商机信息
     * @return 商机列表
     */
    @Override
    public PageResult<BusinessDO> businessList(BusinessListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<BusinessDO> list = this.baseMapper.selectBusinessByPage(dto);
        Page<BusinessDO> page = (Page<BusinessDO>) list;
        PageResult<BusinessDO> result = PageResult.<BusinessDO>builder()
                .total(page.getTotal())
                .rows(page.getResult())
                .build();
        return  result;
    }

    /**
     * 新增商机
     *
     * @param dto 商机信息
     */
    @Override
    public void addBusiness(BusinessAddDTO dto) {
        //参数校验
        if (ObjectUtil.isEmpty(dto.getPhone()) || ObjectUtil.isEmpty(dto.getChannel())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 将DTO转换为实体 bean拷贝
        Business business = BeanUtil.copyProperties(dto, Business.class);
        //补全创建时间
        business.setCreateTime(LocalDateTime.now());
        //补全修改时间
        business.setUpdateTime(LocalDateTime.now());
        //补全状态(待分配)
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        //保存数据
        this.save(business);

    }
}
